package com.futao.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;

import java.util.Properties;

/**
 * @author futao
 * Created on 18-6-7-下午5:26.
 */
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class HibernateConfiguration {


    @Value("${spring.jpa.properties.hibernate.dialect}")
    private String DIALECT;

    @Value("${hibernate.show_sql}")
    private String SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HBM2DDL_AUTO;

    @Value("${entityManager.packagesToScan}")
    private String PACKAGES_TO_SCAN;

    @Resource
    private DataSource dataSource;

    /**
     * @return
     */
    @Bean(value = "sessionFactory")
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
        hibernateProperties.put("hibernate.format_sql", true);
//        hibernateProperties.put("hibernate.cache.use_query_cache", true);

        sessionFactory.setHibernateProperties(hibernateProperties);

        return sessionFactory;
    }

}
